<script lang="ts" setup>
	import { ref, watch } from 'vue'
	import { onClickOutside } from '@vueuse/core'
	import { AreaList, CityResult } from '@/types/goods'
	import request from '@/utils/request'

	defineProps<{
		userAdress?: string
	}>()
	const emits = defineEmits<{
		(e: 'changeCity', value: CityResult): void
	}>()

	const active = ref(false)
	const toggle = () => {
		active.value = !active.value
	}
	const target = ref(null)
	onClickOutside(target, (event) => {
		active.value = false
	})
	watch(active, () => {
		if (!active.value) cityList.value = cachList.value
	})
	const cityList = ref<AreaList[]>([])
	// 备份数据
	const cachList = ref<AreaList[]>([])
	const getCityList = async () => {
		const res = await request.get<AreaList[]>(
			'https://yjy-oss-files.oss-cn-zhangjiakou.aliyuncs.com/tuxian/area.json'
		)
		cityList.value = res.data
		cachList.value = res.data
	}
	getCityList()

	const changeResult = ref({
		provinceCode: '',
		provinceName: '',
		cityCode: '',
		cityName: '',
		countyCode: '',
		countyName: '',
	})

	const selectCity = (city: AreaList) => {
		if (city.level === 0) {
			cityList.value = city.areaList
			changeResult.value.provinceCode = city.code
			changeResult.value.provinceName = city.name
		}
		if (city.level === 1) {
			cityList.value = city.areaList
			changeResult.value.cityCode = city.code
			changeResult.value.cityName = city.name
		}
		if (city.level === 2) {
			changeResult.value.countyCode = city.code
			changeResult.value.countyName = city.name
			active.value = false
			emits('changeCity', changeResult.value)
		}
	}
</script>
<template>
	<div class="xtx-city" ref="target">
		<div class="select" @click="toggle" :class="{ active }">
			<span class="value" v-if="userAdress">{{ userAdress }}</span>
			<span class="placeholder" v-else>请选择配送地址</span>
			<i class="iconfont icon-angle-down"></i>
		</div>
		<div class="option" v-show="active">
			<span class="ellipsis" v-for="item in cityList" :key="item.code" @click="selectCity(item)">{{
				item.name
			}}</span>
		</div>
	</div>
</template>

<style scoped lang="less">
	.xtx-city {
		display: inline-block;
		position: relative;
		z-index: 400;
		.select {
			border: 1px solid #e4e4e4;
			height: 30px;
			padding: 0 5px;
			line-height: 28px;
			cursor: pointer;
			&.active {
				background: #fff;
			}
			.placeholder {
				color: #999;
			}
			.value {
				color: #666;
				font-size: 12px;
			}
			i {
				font-size: 12px;
				margin-left: 5px;
			}
		}
		.option {
			width: 542px;
			border: 1px solid #e4e4e4;
			position: absolute;
			left: 0;
			top: 29px;
			background: #fff;
			min-height: 30px;
			line-height: 30px;
			display: flex;
			flex-wrap: wrap;
			padding: 10px;
			> span {
				width: 130px;
				text-align: center;
				cursor: pointer;
				border-radius: 4px;
				padding: 0 3px;
				&:hover {
					background: #f5f5f5;
				}
			}
		}
	}
</style>
